package org.devocean.groupbuying.service.mail;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.velocity.app.VelocityEngine;
import org.devocean.groupbuying.domain.Article;
import org.devocean.groupbuying.domain.Customer;
import org.devocean.groupbuying.domain.Purchase;
import org.devocean.groupbuying.domain.PurchaseItem;
import org.devocean.groupbuying.domain.SerialKey;
import org.devocean.groupbuying.domain.Voucher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Service
public class MailServiceImpl implements MailService {
	@Autowired
	private JavaMailSender mailSender;
	@Autowired
	private VelocityEngine velocityEngine;

	@Value("#{mailProfile['from']}")
	private String from;

	@Async
	public void notifyNewCustomer(Customer customer) {

		MimeMessage msg = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true);
			helper.setFrom(from);
			helper.setSubject("Welcome to Cloudswave");
			helper.setTo(customer.getEmail());
			final Map<Object, Object> model = new HashMap<Object, Object>();
			model.put("customer", customer);
			helper.setText(
					VelocityEngineUtils
							.mergeTemplateIntoString(
									velocityEngine,
									"org/devocean/groupbuying/service/mail/templates/newAccount.vm",
									model), true);

		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
		try {
			mailSender.send(msg);
			System.out.println("mail sent");
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}

	}

	@Async
	public void notifyUpdatedCustomer(Customer customer) {

		MimeMessage msg = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true);
			helper.setFrom(from);
			helper.setSubject("Cloudswave : update personal informations");
			helper.setTo(customer.getEmail());
			final Map<Object, Object> model = new HashMap<Object, Object>();
			model.put("customer", customer);
			helper.setText(
					VelocityEngineUtils
							.mergeTemplateIntoString(
									velocityEngine,
									"org/devocean/groupbuying/service/mail/templates/accountUpdate.vm",
									model), true);

		} catch (Exception e) {
			System.err.println(e.getMessage());
		}

		try {
			mailSender.send(msg);
			System.out.println("mail sent");
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}

	}

	@Async
	public void sendVoucher(Customer customer, Set<SerialKey> keys) {

		MimeMessage msg = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true);
			helper.setFrom(from);
			helper.setSubject("Deal Voucher from cloudswave.com");
			helper.setTo(customer.getEmail());
			final Map<Object, Object> model = new HashMap<Object, Object>();
			model.put("customer", customer);
			model.put("serialKeys", keys);
			model.put("quantity", keys.size());
			Voucher voucher = keys.iterator().next().getVoucher();

			model.put("voucher", voucher);
			model.put("product", voucher.getDiscount().getDeal().getProduct()
					.getArticlesLocalization().getArticles().iterator().next());
			model.put("plan", voucher.getDiscount().getFormula().getPlan()
					.getArticlesLocalization().getArticles().iterator().next());

			helper.setText(
					VelocityEngineUtils
							.mergeTemplateIntoString(
									velocityEngine,
									"org/devocean/groupbuying/service/mail/templates/sendVoucher.vm",
									model), true);

		} catch (Exception e) {
			System.err.println(e.getMessage());
		}

		try {
			mailSender.send(msg);
			System.out.println("mail sent");

		} catch (Exception e) {
			System.err.println(e.getMessage());
		}

	}

	@Async
	public void confirmPayment(final Purchase purchase) {

		final Customer customer = purchase.getCustomer();

		MimeMessage msg = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true);
			helper.setFrom("CLOUDSWAVE");
			helper.setSubject("Cloudswave payment confirmation");
			helper.setTo(purchase.getCustomer().getEmail());
			final Map<Object, Object> model = new HashMap<Object, Object>();
			model.put("customer", customer);
			model.put("purchase", purchase);
			Iterator<PurchaseItem> itPurchaseItem = purchase.getItems()
					.iterator();
			Iterator<Article> itArticle = itPurchaseItem.next().getDiscount()
					.getDeal().getProduct().getArticlesLocalization()
					.getArticles().iterator();
			model.put("productTitle", itArticle.next().getTitle());

			Map<String, PurchaseItem> items = new HashMap<String, PurchaseItem>();

			for (PurchaseItem item : purchase.getItems()) {
				Iterator<Article> iterator = item.getDiscount().getDeal()
						.getProduct().getArticlesLocalization().getArticles()
						.iterator();
				items.put(iterator.next().getTitle(), item);
			}
			model.put("items", items);

			helper.setText(
					VelocityEngineUtils
							.mergeTemplateIntoString(
									velocityEngine,
									"org/devocean/groupbuying/service/mail/templates/confirmPayment.vm",
									model), true);

		} catch (Exception e) {
			System.err.println(e.getMessage());
		}

		try {
			mailSender.send(msg);
			System.out.println("mail sent");
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}

	}

	@Async
	public void forgotPassword(Customer customer, String uri) {
		MimeMessage msg = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(msg, true);
			helper.setFrom("CLOUDSWAVE");
			helper.setSubject("Cloudswave Password redefinition");
			helper.setTo(customer.getEmail());
			final Map<Object, Object> model = new HashMap<Object, Object>();
			model.put("customer", customer);
			model.put("URI", uri);

			helper.setText(
					VelocityEngineUtils
							.mergeTemplateIntoString(
									velocityEngine,
									"org/devocean/groupbuying/service/mail/templates/forgotPassword.vm",
									model), true);

			try {
				mailSender.send(msg);
				System.out.println("mail sent");
			} catch (Exception e) {
				System.err.println(e.getMessage());
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

	}
}
